<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';

import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import {
  Alert as AAlert,
  Button as AButton,
  Divider as ADivider,
  Form as AForm,
  FormItem as AFormItem,
  InputNumber as AInputNumber,
  Modal as AModal,
  Select as ASelect,
  Spin as ASpin,
  Switch as ASwitch,
  Textarea as ATextarea,
  message,
  Modal,
} from 'ant-design-vue';

import { productList } from '#/api/hm/product';
import { saleOrderPickUp } from '#/api/hm/saleOrderPickUp';
import { ImageUpload } from '#/components/upload';

// --- 组件通信 (Props & Emits) ---
const props = defineProps({
  visible: { type: Boolean, default: false },
  orderId: { type: [String, Number], required: true },
  orderData: { type: Object, default: () => ({}) },
});

const emit = defineEmits(['update:visible', 'success']);

// --- 状态管理 ---
const loading = ref(false);
const formRef = ref();
const isSupplementaryMode = ref(false);

const formState = reactive({
  productPickupQty: undefined,
  giftPickups: [] as {
    giftProductId: number;
    maxQty: number;
    pickupQty: number | undefined;
    productName: string;
  }[],
  supplementaryItems: [] as {
    key: number;
    maxQty?: number;
    newProductId?: number;
    originalProductId?: number;
    quantity?: number;
    type: 'gift' | 'product';
  }[],
  attachments: [] as string[],
  remark: '',
});

// --- 数据加载与计算属性 ---
const supplementaryProductOptions = ref<{ label: string; value: string }[]>([]);
const supplementaryGiftOptions = ref<{ label: string; value: string }[]>([]);

const mainProduct = computed(() => props.orderData?.orderItemList?.[0] || {});
const giftList = computed(() => props.orderData?.giftList || []);

const canAddSupplementaryProduct = computed(() => {
  return !formState.supplementaryItems.some((item) => item.type === 'product');
});

const canAddSupplementaryGift = computed(() => {
  const supplementaryGiftCount = formState.supplementaryItems.filter(
    (item) => item.type === 'gift',
  ).length;
  const originalGiftCount = giftList.value.length;
  return supplementaryGiftCount < originalGiftCount;
});

const originalGiftOptions = computed(() => {
  const selectedOriginalGiftIds = new Set(
    formState.supplementaryItems
      .filter((item) => item.type === 'gift')
      .map((item) => item.originalProductId),
  );
  return giftList.value.map((gift: any) => ({
    label: gift.giftProductName,
    value: gift.giftProductId,
    disabled: selectedOriginalGiftIds.has(gift.giftProductId),
  }));
});

// --- 核心方法 ---
const validateQuantity = (value: number, maxQty: number) => {
  if (value === null || value === undefined) {
    return Promise.resolve();
  }
  if (value > maxQty) {
    return Promise.reject('数量不能超过剩余量');
  }
  return Promise.resolve();
};

const validateSupplementaryQuantity = (
  value: number,
  maxQty: number | undefined,
) => {
  if (value === null || value === undefined) {
    return Promise.resolve();
  }
  if (maxQty !== undefined && value > maxQty) {
    return Promise.reject('数量不能超过最大值');
  }
  return Promise.resolve();
};

// 初始化表单
function initializeForm() {
  loading.value = true;
  formRef.value?.resetFields();
  isSupplementaryMode.value = false;

  formState.productPickupQty = undefined;
  formState.giftPickups = giftList.value.map((gift: any) => ({
    giftProductId: gift.giftProductId,
    productName: gift.giftProductName,
    pickupQty: undefined, // 默认不填充已提货数量
    maxQty: gift.giftNum - gift.giftUsedNum,
  }));

  formState.supplementaryItems = [];
  formState.attachments = [];
  formState.remark = '';
  loading.value = false;
}

// 加载补充提货的下拉选项
async function loadSupplementaryOptions() {
  try {
    // 并行获取产品和赠品列表
    const [productRes, giftRes] = await Promise.all([
      productList({
        pageNum: 1,
        pageSize: 999,
        status: '0',
        productType: 'CP',
      }),
      productList({
        pageNum: 1,
        pageSize: 999,
        status: '0',
        productType: 'ZP',
      }),
    ]);

    supplementaryProductOptions.value = (productRes.rows || []).map((item) => ({
      label: item.productName,
      value: item.productId.toString(),
    }));

    supplementaryGiftOptions.value = (giftRes.rows || []).map((item) => ({
      label: item.productName,
      value: item.productId.toString(),
    }));
  } catch (error) {
    console.error('加载补充产品选项失败:', error);
    message.error('加载补充产品选项失败');
  }
}

watch(
  () => props.visible,
  (isVisible) => {
    if (isVisible) {
      initializeForm();
      loadSupplementaryOptions(); // 弹窗打开时加载选项
    }
  },
);

function addSupplementaryItem(type: 'gift' | 'product') {
  if (type === 'gift' && !canAddSupplementaryGift.value) {
    message.warning('已为所有原始赠品添加了替换项，无法再添加。');
    return;
  }
  if (type === 'product' && !canAddSupplementaryProduct.value) {
    message.warning('只能为订单主商品添加一条替换项。');
    return;
  }
  const newItem: any = {
    key: Date.now(),
    type,
    originalProductId:
      type === 'product' ? mainProduct.value.productId : undefined,
    maxQty:
      type === 'product' ? mainProduct.value.remainingQuantity : undefined,
  };
  formState.supplementaryItems.push(newItem);
}

function removeSupplementaryItem(itemToRemove: any) {
  const index = formState.supplementaryItems.indexOf(itemToRemove);
  if (index !== -1) {
    formState.supplementaryItems.splice(index, 1);
  }
}

function handleOriginalGiftChange(item: any) {
  const selectedGift = giftList.value.find(
    (g: any) => g.giftProductId === item.originalProductId,
  );
  if (selectedGift) {
    item.maxQty = selectedGift.giftNum - selectedGift.giftUsedNum;
    item.quantity = undefined;
  } else {
    item.maxQty = undefined;
    item.quantity = undefined;
  }
}

function handleCancel() {
  emit('update:visible', false);
}

async function handleSubmit() {
  try {
    await formRef.value.validate();
    loading.value = true;

    let payload;
    if (isSupplementaryMode.value) {
      if (
        formState.supplementaryItems.every(
          (item) => !item.newProductId || !item.quantity || item.quantity <= 0,
        )
      ) {
        message.warning('请至少填写一条有效的补充提货信息');
        loading.value = false;
        return;
      }

      payload = {
        orderId: props.orderId,
        type: 'supplementary',
        pickupDeptId: props.orderData?.saleDept,
        items: formState.supplementaryItems
          .filter(
            (item) => item.newProductId && item.quantity && item.quantity > 0,
          )
          .map((item) => ({
            originalProductId: item.originalProductId,
            productId: item.newProductId,
            quantity: item.quantity,
            type: item.type,
          })),
        remark: formState.remark,
        attachments: formState.attachments,
      };
    } else {
      let totalPickupQty = 0;
      const pickupItems: any[] = [];

      const productQty = formState.productPickupQty || 0;
      if (productQty > 0) {
        pickupItems.push({
          productId: mainProduct.value.productId,
          quantity: productQty,
          type: 'product',
        });
        totalPickupQty += productQty;
      }

      formState.giftPickups.forEach((gift) => {
        const giftQty = gift.pickupQty || 0;
        if (giftQty > 0) {
          pickupItems.push({
            productId: gift.giftProductId,
            quantity: giftQty,
            type: 'gift',
          });
          totalPickupQty += giftQty;
        }
      });

      if (totalPickupQty <= 0) {
        message.warning('总提货数量必须大于0');
        loading.value = false;
        return;
      }
      payload = {
        orderId: props.orderId,
        type: 'normal',
        items: pickupItems,
        remark: formState.remark,
        attachments: formState.attachments,
      };
    }
    Modal.confirm({
      title: '提示',
      okType: 'danger',
      content: `请核对信息是否正确，确定提交吗？`,
      onOk: async () => {
        await saleOrderPickUp(payload);
        message.success('操作成功！');
        emit('success');
        handleCancel();
      },
    });
  } catch (error) {
    console.error('提货提交失败:', error);
  } finally {
    loading.value = false;
  }
}
const filterProductOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase());
};
</script>

<template>
  <AModal
    v-model:visible="props.visible"
    title="发起提货"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirm-loading="loading"
    width="800px"
    destroy-on-close
  >
    <ASpin :spinning="loading">
      <AForm ref="formRef" :model="formState" layout="vertical">
        <AFormItem label="提货模式">
          <ASwitch
            v-model:checked="isSupplementaryMode"
            checked-children="补充提货"
            un-checked-children="正常提货"
          />
          <p class="mt-1 text-xs text-gray-400">
            当商品或赠品无法正常提货时（如已停产），可启用补充提货模式更换为其他等价产品。
          </p>
        </AFormItem>
        <ADivider />

        <!-- 正常提货区域 -->
        <div v-if="!isSupplementaryMode">
          <AAlert
            :message="`主商品【${mainProduct.productName}】剩余提货量为：${mainProduct.remainingQuantity}`"
            type="info"
            show-icon
            class="mb-4"
          />
          <AFormItem
            label="本次提货数量"
            name="productPickupQty"
            :rules="[
              {
                validator: (_, value) =>
                  validateQuantity(value, mainProduct.remainingQuantity),
              },
            ]"
          >
            <AInputNumber
              v-model:value="formState.productPickupQty"
              placeholder="请输入提货数量"
              :min="0"
              :max="mainProduct.remainingQuantity"
              :precision="2"
              style="width: 100%"
            />
          </AFormItem>

          <div v-if="formState.giftPickups.length > 0">
            <ADivider orientation="left" dashed>赠品列表</ADivider>
            <div
              v-for="(gift, index) in formState.giftPickups"
              :key="gift.giftProductId"
              class="gift-item"
            >
              <AFormItem
                :label="`${gift.productName} (剩余 ${gift.maxQty})`"
                :name="['giftPickups', index, 'pickupQty']"
                :rules="[
                  {
                    validator: (_, value) =>
                      validateQuantity(value, gift.maxQty),
                  },
                ]"
              >
                <AInputNumber
                  v-model:value="gift.pickupQty"
                  placeholder="输入数量"
                  :min="0"
                  :max="gift.maxQty"
                  :precision="2"
                  style="width: 100%"
                />
              </AFormItem>
            </div>
          </div>
        </div>

        <!-- 补充提货区域 -->
        <div v-if="isSupplementaryMode">
          <div class="supplementary-controls">
            <AButton
              type="dashed"
              @click="addSupplementaryItem('product')"
              :disabled="!canAddSupplementaryProduct"
              size="small"
            >
              <PlusOutlined /> 添加补充产品
            </AButton>
            <AButton
              type="dashed"
              @click="addSupplementaryItem('gift')"
              :disabled="!canAddSupplementaryGift"
              size="small"
              class="ml-2"
            >
              <PlusOutlined /> 添加补充赠品
            </AButton>
          </div>
          <ADivider v-if="formState.supplementaryItems.length > 0" />

          <div
            v-for="(item, index) in formState.supplementaryItems"
            :key="item.key"
            class="supplementary-item"
          >
            <div class="supplementary-item-content">
              <AFormItem
                :name="['supplementaryItems', index, 'originalProductId']"
                label="原产品"
                :rules="[{ required: true, message: '请选择要替换的原产品' }]"
              >
                <ASelect
                  v-if="item.type === 'product'"
                  v-model:value="item.originalProductId"
                  placeholder="选择原产品"
                  disabled
                >
                  <a-select-option :value="mainProduct.productId">
                    {{ mainProduct.productName }}
                  </a-select-option>
                </ASelect>
                <ASelect
                  v-else
                  v-model:value="item.originalProductId"
                  placeholder="请选择要替换的赠品"
                  @change="handleOriginalGiftChange(item)"
                >
                  <a-select-option
                    v-for="opt in originalGiftOptions"
                    :key="opt.value"
                    :value="opt.value"
                    :disabled="
                      opt.disabled && opt.value !== item.originalProductId
                    "
                  >
                    {{ opt.label }}
                  </a-select-option>
                </ASelect>
              </AFormItem>
              <AFormItem
                :name="['supplementaryItems', index, 'newProductId']"
                label="替换为"
                :rules="[{ required: true, message: '请选择替换产品' }]"
              >
                <ASelect
                  v-model:value="item.newProductId"
                  placeholder="选择替换产品"
                  show-search
                  :filter-option="filterProductOption"
                  :options="
                    item.type === 'product'
                      ? supplementaryProductOptions
                      : supplementaryGiftOptions
                  "
                />
              </AFormItem>
              <AFormItem
                :name="['supplementaryItems', index, 'quantity']"
                :label="`补充数量 (最大 ${item.maxQty || 'N/A'})`"
                :rules="[
                  { required: true, message: '请输入数量' },
                  {
                    validator: (_, value) =>
                      validateSupplementaryQuantity(value, item.maxQty),
                  },
                ]"
              >
                <AInputNumber
                  v-model:value="item.quantity"
                  placeholder="数量"
                  :min="1"
                  :max="item.maxQty"
                  :precision="2"
                  style="width: 100%"
                />
              </AFormItem>
            </div>
            <AButton
              type="dashed"
              danger
              @click="removeSupplementaryItem(item)"
            >
              <template #icon>
                <DeleteOutlined />
              </template>
            </AButton>
          </div>
        </div>

        <ADivider dashed />
        <AFormItem
          label="证明材料"
          name="attachments"
          :rules="[{ required: true, message: '请上传证明材料' }]"
        >
          <ImageUpload
            v-model:value="formState.attachments"
            :max-number="3"
            result-field="url"
            multiple
          />
        </AFormItem>
        <AFormItem label="备注信息" name="remark">
          <ATextarea
            v-model:value="formState.remark"
            placeholder="请输入备注信息（可选）"
            :rows="3"
          />
        </AFormItem>
      </AForm>
    </ASpin>
  </AModal>
</template>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

.mt-1 {
  margin-top: 4px;
}

.ml-2 {
  margin-left: 8px;
}

.text-gray-400 {
  color: #9ca3af;
}

.text-xs {
  font-size: 12px;
}

.gift-item {
  margin-bottom: 0;
}

.supplementary-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 16px;
}

.supplementary-item-content {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.supplementary-controls {
  margin-bottom: 16px;
}
</style>
